package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"

	"github.com/golang/glog"
)

var VERSION string

func init() {
	VERSION = os.Getenv("VERSION")
	glog.Infof("read env {VERSION} : %s", VERSION)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("VERSION", VERSION)
	for name, header := range r.Header {
		for _, value := range header {
			w.Header().Add(name, value)
		}
	}
	fmt.Fprintf(w, "this is http server")

	accessLog := fmt.Sprintf("access log => remote ip : %s, method : %s, path : %s, query : %s",
		r.RemoteAddr, r.Method, r.RequestURI, r.URL.RawQuery)
	fmt.Println(accessLog)
	glog.Info(accessLog)
}

func healthz(w http.ResponseWriter, r *http.Request) {
	glog.Infof("healthz remote ip : %s", r.RemoteAddr)
	w.WriteHeader(http.StatusOK)
}

// set env : export VERSION=v1.0
// go run main.go -log_dir=log
func main() {
	flag.Parse()
	defer glog.Flush()

	glog.Info("starting http server...")
	http.HandleFunc("/healthz", healthz)
	http.HandleFunc("/", rootHandler)
	glog.Info("start listen 80")
	http.ListenAndServe(":80", nil)
}
